"""
    Controller for editing migrations, based on `student_migration_for_teacher_lookup`
    view with filtration by teacher's groups.
"""

import turbogears
from mnemoply import model
from mnemoply.controllers.lookup import LookupController, TableCol, TableLookupDataSource
from mnemoply.controllers.crud import CRUDController

def getGroups(user):
    """
        Returns groups ID, where user's person is teacher.
    """
    if user.person is None:
        return []
    else:
        return [g.id for g in model.Group.selectBy(teacher = user.person)]

class StudentMigrationForTeacherDataSource(TableLookupDataSource):
    """
        Provides `student_migration_for_teacher_lookup` with filtration by groups.
    """

    ed_groups = []
    def __init__(self):
        TableLookupDataSource.__init__(self, 'student_migration_for_teacher_lookup')

    def _buildWhereChunks(self, request):
        chunks = TableLookupDataSource._buildWhereChunks(self, request)
        if len(self.ed_groups):
            chunks.append("(" + " OR ".join(["group_from_id = %d" % g for g in self.ed_groups]) + ")")
        return chunks

class MigrationForTeacherController(LookupController, CRUDController):
    model_object = model.StudentMigration

    lookup_columns = [
        TableCol(name='student', caption=_('Student')),
        TableCol(name='school_form', caption=_('School form')),
        TableCol(name='teacher_plan', caption=_('Teacher wish plan')),
        TableCol(name='cache_title', caption=_('Group')),
        TableCol(name='office', caption=_('Office')),
        TableCol(name='avg_mark', caption=_('Average mark')),
        TableCol(name='opponents', caption=_('Opponents')),
        TableCol(name='comment', caption=_('Comment'), hidden=True),
        TableCol(name='year', caption=_('Year'), hidden=True),
        TableCol(name='behaviour_comment', caption=_('Behaviour comment'), hidden=True),
        TableCol(name='health_problems', caption=_('Health problems'), hidden=True),
        ]

    view_fields = [
        'studentID', 'agreementID', 'officeID', 'year',
        'groupFromID',
        'planID',
        'teacherID',
        'initialPlanMethodologistWishID',
        'initialPlanTeacherWishID',
        'friends', 'opponents', 'avgMark', 'healthProblems',
        'possibleDayID',
        'behaviourComment', 'comment',
        ]

    edit_fields = [
        'avgMark',
        'initialPlanTeacherWishID',
        'opponents',
        'behaviourComment',
        'comment',
        'healthProblems',
        ]

    @turbogears.expose(template="genshi:mnemoply.templates.lib.lookup")
    def list(self):
        user = turbogears.identity.current.user
        self.data_source.ed_groups = getGroups(user)
        return LookupController.list(self)

    def _get_edit_form(self, obj=None):
        form = CRUDController._get_edit_form(self)

        # Changed InitialPlanTeacherWishID field
        if obj.groupFrom is not None:
            last_year_plan = obj.groupFrom.initialPlan
            pts = model.PlanTransfer.selectBy(currentPlan=last_year_plan)
            form.fields[1].records = [pt.nextPlan for pt in pts]
        return form

    def __init__(self):
        LookupController.__init__(self,
            data_source=StudentMigrationForTeacherDataSource(),
            columns=self.lookup_columns,
            title=self.model_object.model_title,
        )
        CRUDController.__init__(self, model_object=self.model_object)
        self.title = _("Migration for teacher")
        self.local_menu = []

exposed = MigrationForTeacherController()
